#include "TestFramework.h"
#include "API/WebCore.h"

#define WIDTH	600
#define HEIGHT	600
#define LENGTH_SEC	1

class Test_GetElementById : public Test, public Awesomium::WebViewListener
{
	Awesomium::WebView* webView;
  bool _hasLoaded;

public:
	Test_GetElementById() : Test("GetElementById")
    , _hasLoaded(false)
	{
		webView = Awesomium::WebCore::Get().createWebView(WIDTH, HEIGHT);
    webView->setListener(this);
		webView->loadFile("tests/GetElementById.html");
    while (!_hasLoaded)
    {
      Awesomium::WebCore::Get().update();
      SleepWait(10);
    }
	}

	~Test_GetElementById()
	{
		webView->destroy();
	}

	bool run()
	{
		log("Running");

		unsigned char* buffer = new unsigned char[WIDTH * HEIGHT * 4];

		timer t;
		t.start();
		int loopCount = 0;
		int renderCount = 0;

 		while(t.elapsed_time() < LENGTH_SEC)
		{
      {
			  Awesomium::FutureJSValue futureVal = webView->executeJavascriptWithResult("getElementsCount()");
			  double result = futureVal.get().toDouble();

			  if((int)result != 7)
        {
				  log("Test failed, 'getElementsCount' should return 7.");
          LOG(result);
				  return false;
        }
      }
      loopCount++;
			SleepWait(1);
		}

		delete[] buffer;

		logTestValue("RenderSync_LoopCount", loopCount / (double)LENGTH_SEC);
		logTestValue("RenderSync_RenderCount", renderCount / (double)LENGTH_SEC);

		return true;
	}

  void onBeginNavigation(const std::string& url, const std::wstring& frameName) {}
	void onBeginLoading(const std::string& url, const std::wstring& frameName, int statusCode, const std::wstring& mimeType) {}
	void onFinishLoading() { _hasLoaded = true; }
	void onCallback(const std::string& name, const Awesomium::JSArguments& args) {}
	void onReceiveTitle(const std::wstring& title, const std::wstring& frameName) {}
	void onChangeTooltip(const std::wstring& tooltip) {}
#if defined(_WIN32)
	void onChangeCursor(HCURSOR cursor) {}
#endif
	void onChangeKeyboardFocus(bool isFocused) {}
	void onChangeTargetURL(const std::string& url) {}
	void onCreateNewWebView() {};
};